package com.wynn.configuration;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@EnableScheduling
@EnableAsync
@Configuration
public class ScheduledConfig {

    @Value("${executorConfig.core-pool-size}")
    private int corePoolSize;
    @Value("${executorConfig.max-pool-size}")
    private int maxPoolSize;
    @Value("${executorConfig.queue-capacity}")
    private int queueCapacity;
    @Value("${executorConfig.keep-alive-time}")
    private int keepAliveSeconds;

    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        executor.setCorePoolSize(corePoolSize);
        //设置最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //设置任务队列容量
        executor.setQueueCapacity(queueCapacity);
        //设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(keepAliveSeconds);
        //设置默认线程名称(线程前缀名称，有助于区分不同线程池之间的线程比如：taskExecutor-query-)
        executor.setThreadNamePrefix("taskExecutor-query-");
        //设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //设置允许核心线程超时，默认是false
        executor.setAllowCoreThreadTimeOut(false);
        return executor;
    }


}

